<?php

namespace app\teacher\controller\learn;

use app\common\controller\Frontend;
use app\common\enums\AccountTypeEnum;
use app\common\model\banxi\learn\LearnSayAntiForgetting as LearnSayAntiForgettingModel;
use app\common\model\banxi\learn\LearnSayAntiForgettingSentence;
use app\common\model\banxi\learn\LearnSayQuestionAnswerRecord;
use app\common\model\banxi\learn\LearnSayQuestionRecord;
use app\common\model\banxi\organization\Organization;
use app\common\model\banxi\say\SayTeachSentence;
use app\common\model\banxi\student\Student;
use app\common\service\learn\LearnSkRecordService;
use think\facade\Db;
use think\facade\Log;

/*
 * 全科抗遗忘
 * */

class LearnSayAntiForgetting extends Frontend
{
    protected array $noNeedLogin = [''];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /*
     * 创建抗遗忘
     * */
    public function createSayAntiForgetting()
    {
        $recordId = $this->request->post('recordId', 0);
        $time = $this->request->post('time', '');

        // 根据预约ID查询上课记录
        $learnSayQuestionRecordModel = new LearnSayQuestionRecord();
        $learnSayQuestionRecord = $learnSayQuestionRecordModel
            ->where('id', $recordId)
            ->where('isSubmit', 1)
            ->find();
        if (!$learnSayQuestionRecord) {
            $this->fail('请选择要创建的记录');
        }
        if (!$time) {
            $this->fail('请选择时间');
        }
        $LearnSayAntiForgettingModel = new LearnSayAntiForgettingModel();

        $trainerId = $this->auth->id;
        $groupId = createPasswordSalt();

        // 检查是否已经为该上课记录创建过抗遗忘记录
        $exists = $LearnSayAntiForgettingModel
            ->where('questionRecordId', $recordId)
            ->find();
        if ($exists) {
            $this->fail('该课程已创建抗遗忘记录');
        }
        // 构造数据创建从明天开始算连续5天的抗遗忘记录
        $records = [];
        for ($i = 0; $i < 4; $i++) {
            if ($i == 2) {
                continue;
            }
            $date = date('Y-m-d', strtotime("+$i day"));
            $records[] = [
                'questionRecordId' => $recordId,
                'sayTeachSentenceId' => $learnSayQuestionRecord['sayTeachSentenceId'],
                'sayTeachSentenceName' => $learnSayQuestionRecord['sayTeachSentenceName'],
                'groupId' => $groupId,
                'trainerId' => $trainerId,
                'studentId' => $learnSayQuestionRecord['studentId'],
                'studentOrgId' => $learnSayQuestionRecord['studentOrgId'],
                'trainerAntiForgettingId' => $learnSayQuestionRecord['trainerId'],
                'date' => $date,
                'time' => $time,
            ];
        }
        $LearnSayQuestionAnswerRecordModel = new LearnSayQuestionAnswerRecord();
        $LearnSayQuestionAnswerRecordList = $LearnSayQuestionAnswerRecordModel->where([
            ['recordId', '=', $recordId],
            ['isCorrect', '>', -1]
        ])->select();
        $LearnSayQuestionAnswerRecordData = [];
        foreach ($LearnSayQuestionAnswerRecordList as $item) {
            $LearnSayQuestionAnswerRecordData[] = [
                'questionRecordId' => $recordId,
                'groupId' => $groupId,
                'parentTeachSentenceId' => $item['parentTeachSentenceId'],
                'sayTeachSentenceId' => $item['sayTeachSentenceId'],
                'sayTeachSentenceName' => $item['sayTeachSentenceName'],
                'sentenceEn' => $item['sentenceEn'],
                'sentenceZh' => $item['sentenceZh'],
                'sentencePhonetic' => $item['sentencePhonetic'],
                'sentenceAudio' => $item['sentenceAudio'],
                'sentenceImage' => $item['sentenceImage'],
                'sentenceWordColor' => $item['sentenceWordColor'],
            ];
        }

        // 批量插入数据
        Db::startTrans();
        try {
            $LearnSayAntiForgettingModel->saveAll($records);
            $LearnSayAntiForgettingSentenceModel = new LearnSayAntiForgettingSentence();
            $LearnSayAntiForgettingSentenceModel->saveAll($LearnSayQuestionAnswerRecordData);
            //更新学习记录
            $learnSayQuestionRecord->isCreateAntiForgetting = 1;
            $learnSayQuestionRecord->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('创建抗遗忘记录失败: ' . $e->getMessage());
            $this->fail('创建失败');
        }

        $this->ok('ok');
    }


    /**
     * 查询-我的抗遗忘记录
     *
     * @return \think\response\Json
     */
    public function listMyList()
    {
        $isAll = $this->request->get('isAll', 0);
        // 获取当前用户ID
        $trainerId = $this->auth->id;
        $where = [
            ['trainerAntiForgettingId', '=', $trainerId]
        ];
        if (!$isAll) {
            $where[] = ['date', '<=', date('Y-m-d')];
        }

        // 查询符合条件的抗遗忘记录（日期大于等于今天）
        $LearnSubjectAntiForgettingModel = new LearnSayAntiForgettingModel();
        $forgettingList = $LearnSubjectAntiForgettingModel
            ->with([
                'student' => function ($query) {
                    $query->field('id,name');
                }])
            ->where($where)
            ->order('status', 'asc')
            ->select();

        // 按日期分组包装结果
        $result = $LearnSubjectAntiForgettingModel->wrapperReviewDate($forgettingList);

        $this->ok('操作成功', $result);
    }

    /*
     * 开始抗遗忘
     * */
    public function startAntiForgetting()
    {
        $id = $this->request->post('id', 0);

        $trainerId = $this->auth->id;

        $LearnSkRecordService = new LearnSkRecordService();
        $info = $LearnSkRecordService->startSayForgetting($id, $trainerId,AccountTypeEnum::TRAINER);
        $this->ok('操作成功', $info);
    }

    public function listForgettingData()
    {
        $forgettingId = $this->request->get('forgettingId');
        if (empty($forgettingId)) {
            $this->fail('请选择要查看的记录');
        }
        $LearnSayAntiForgettingModel = new LearnSayAntiForgettingModel();
        $reviewData = $LearnSayAntiForgettingModel->where('id', $forgettingId)->find();
        if (empty($reviewData)) {
            $this->fail('数据不存在');
        }
        $sayTeachSentenceModel = new SayTeachSentence();
        $forgettingAnswerList = $sayTeachSentenceModel->alias('a')
            ->join('banxi_learn_say_anti_forgetting_answer b', 'b.sayTeachSentenceId = a.id')
            ->where([
                'b.forgettingId' => $forgettingId,
                'b.del' => 0
            ])->field('b.id,a.sentenceEn,a.sentenceZh,a.sentencePhonetic,a.sentenceAudio,a.sentenceImage,a.sentenceWordColor,a.question,a.answer,b.isCorrect,b.listenCorrect,b.translationCorrect,b.questionCorrect')->select();
        if (empty($forgettingAnswerList)) {
            $this->fail('数据不存在');
        }
        foreach ($forgettingAnswerList as $item) {
            $item['questionList'] = $sayTeachSentenceModel->splitQuestion($item['question'], $item['answer']);
        }
        $this->ok('ok', $forgettingAnswerList);
    }

    /*
     * 结束抗遗忘
     * */
    public function endAntiForgetting()
    {
        $forgettingId = $this->request->post('forgettingId', 0);
        $answerList = $this->request->post('answerList', null, null);
        if (!$answerList) {
            $this->fail('请选择掌握状态');
        }
        $trainerId = $this->auth->id;
        $LearnSkRecordService = new LearnSkRecordService();
        $LearnSkRecordService->answerSayForgetting($forgettingId, $trainerId, AccountTypeEnum::TRAINER, $answerList);
        $this->ok();
    }

    /*
     * 查询-抗遗忘报告
     * */
    public function getForgettingReport()
    {
        $forgettingId = $this->request->get('forgettingId');
        $LearnSubjectAntiForgettingModel = new LearnSayAntiForgettingModel();
        $record = $LearnSubjectAntiForgettingModel
            ->where([
                'id' => $forgettingId
            ])
            ->find();
        if (!$record) {
            $this->fail('抗遗忘记录不存在');
        }

        $studentInfo = null;
        if ($record['studentId']) {
            $studentInfo = Student::with([
                'gradeInfo' => function ($query) {
                    $query->field('id,name');
                },
                'organizationBaseInfo' => function ($query) {
                    $query->field('id,name,managerName');
                }
            ])->where(['id' => $record['studentId']])->field('id,avatar,name,organizationId,englishLevel')->find();
            if ($studentInfo['organizationId'] == 0) {
                $organizationModel = new Organization();
                $studentInfo['organizationBaseInfo'] = $organizationModel->getOrganizationInfo();
            }
        }
        $record['student'] = $studentInfo;
        $sayTeachSentenceModel = new SayTeachSentence();
        $list = $sayTeachSentenceModel->alias('a')
            ->join('banxi_learn_say_anti_forgetting_answer b', 'b.sayTeachSentenceId = a.id')
            ->where([
                ['b.forgettingId', '=', $forgettingId],
                ['b.del', '=', 0],
                ['b.isCorrect', '=', 0]
            ])->field('b.id,a.sentenceEn,a.sentenceZh,a.sentenceAudio,b.isCorrect,b.listenCorrect,b.translationCorrect,b.questionCorrect')->select();

        $this->ok('操作成功', ['forgettingRecord' => $record, 'list' => $list]);
    }
}